<?php

namespace App\Admin\Controllers\Account;

use App\Admin\Models\Account;
use App\Admin\Models\SiteCompany;
use App\Admin\Models\SiteDefaultCategory;
use App\Store\Models\Basic\GoodsCabinetgroup;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\GoodsMetal;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Admin\Models\SiteStore;

use App\Admin\Validate\Account\Store as ValidateAccountStore;
use App\Common\Services\Admin\Common as AdminCommon;
use App\Common\Services\CommonExcelExport;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Maatwebsite\Excel\Facades\Excel;

use App\Common\Services\Store\Common;

class StoreController extends Controller
{
    /**
     * 获取详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteStore::with(['companyinfo', 'adminuserinfo', 'brandinfo', 'businessmeminfo', 'customerserviceinfo'])->where(['id' => $id])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $info->store_file_path = json_decode($info->store_file_path, true);
        $info->contract_file_path = json_decode($info->contract_file_path, true);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $list = SiteStore::getList($request);
        foreach ($list['list'] as &$val) {
            $val['end_days'] = ceil(($val['contract_end_at'] - time()) / 86400);
        }

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 新增门店
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only([
            'p_code', 'c_code', 'd_code', 'cp_id', 'address_area', 'store_name', 'is_can_use', 'brand_id', 'soft_base_fee', 'soft_year_fee', 'contract_at', 'contract_years', 'contract_end_at', 'business_mem_id', 'contract_file_path', 'store_file_path', 'contact_name', 'contact_phone', 'customer_service_id','is_training', 'remark'
        ]);

        $Validate = new ValidateAccountStore;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }


        $data = $req_data;
        $data['is_can_use'] = intval($data['is_can_use']) == 1 ? intval($data['is_can_use']) : 2;
        $data['contract_at'] = strtotime($data['contract_at']) > 0 ? strtotime($data['contract_at']) : intval($data['contract_at']);
        $data['contract_end_at'] = strtotime($data['contract_end_at']) > 0 ? strtotime($data['contract_end_at']) : intval($data['contract_end_at']);
        if ($data['contract_at'] <= 0) {
            $data['contract_end_at'] = time() + 20 * 86400;
        } else {
            if ($data['contract_end_at'] <= time()) {
                return response()->json(['code' => '001', 'msg' => '无效到期时间']);
            }
        }
        $data['contract_years'] = intval($data['contract_years']);
        $data['brand_id'] = empty($data['brand_id']) ? 0 : $data['brand_id'];
        $data['customer_service_id'] = intval($data['customer_service_id']);
        $data['contract_file_path'] = is_array($data['contract_file_path']) ? json_encode($data['contract_file_path']) : json_encode(is_array(json_decode($data['contract_file_path'], true)) ? json_decode($data['contract_file_path'], true) : []);
        $data['store_file_path'] = is_array($data['store_file_path']) ? json_encode($data['store_file_path']) : json_encode(is_array(json_decode($data['store_file_path'], true)) ? json_decode($data['store_file_path'], true) : []);
        $data['create_at'] = time();
        $data['update_at'] = time();
        $data['audit_status'] = 2; //提交成功直接提交审核
        if ($data['contract_at'] > 0) {
            $data['contract_audit_status'] = 2;
        }
        $data['soft_base_fee'] = intval($data['soft_base_fee']);
        $data['soft_year_fee'] = intval($data['soft_year_fee']);


        $data['admin_user_id'] = AdminCommon::getCurrentAdminId($request);
        DB::beginTransaction();
        try {

            $store = SiteStore::create($data);
            // 添加默认数据
            $this->addCategoryDefault(['cp_id' => $data['cp_id'], 'store_id' => $store->id]);
            DB::commit();
            return response()->json(['code' => '000', 'msg' => '新增门店成功']);

        } catch (\Exception $e) {
            DB::rollBack();
            info('新增门店失败' . $e->getMessage());
            return response()->json(['code' => '000', 'msg' => '新增门店失败']);
        }

    }

    /**
     * 编辑门店
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id', 'p_code', 'c_code', 'd_code', 'address_area', 'store_name', 'is_can_use', 'brand_id', 'soft_base_fee', 'soft_year_fee', 'contract_at', 'contract_years', 'contract_end_at', 'business_mem_id', 'contract_file_path', 'store_file_path', 'contact_name', 'contact_phone', 'customer_service_id','is_training', 'remark']);

        $Validate = new ValidateAccountStore('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $info = SiteStore::where([['id', $req_data['id']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '门店参数错误']);
        }
        $data = $req_data;
        unset($data['id']);
        $data['update_at'] = time();
        // $data['audit_status'] = 2;

        $data['contract_at'] = strtotime($data['contract_at']) > 0 ? strtotime($data['contract_at']) : intval($data['contract_at']);
        $data['contract_end_at'] = strtotime($data['contract_end_at']) > 0 ? strtotime($data['contract_end_at']) : intval($data['contract_end_at']);

        if ($data['contract_end_at'] <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效到期时间']);
        }
        if((int)$data['is_can_use']==1){
            if ($data['contract_end_at'] < time()) {
                $data['is_can_use'] = 2;
            }elseif ($data['contract_end_at']>0&& $data['contract_end_at']>=time()){
                $data['is_can_use'] = 1;
            }
        }

        if (($info->contract_at == 0 && $data['contract_at'] > 0) || ($info->soft_year_fee != $data['soft_year_fee']) || ($info->contract_end_at > 0 && ($data['contract_end_at'] != $info->contract_end_at)) || $info->contract_audit_status == 4) {
            $data['contract_audit_status'] = 2;
        }

        if ($info->audit_status == 4) { //审核取消后，编辑完成自动变成审核中，需要再次审核
            $data['audit_status'] = 2;
        }

        $data['contract_years'] = intval($data['contract_years']);
        $data['customer_service_id'] = intval($data['customer_service_id']);
        $data['contract_file_path'] = is_array($data['contract_file_path']) ? json_encode($data['contract_file_path']) : json_encode(is_array(json_decode($data['contract_file_path'], true)) ? json_decode($data['contract_file_path'], true) : []);
        $data['store_file_path'] = is_array($data['store_file_path']) ? json_encode($data['store_file_path']) : json_encode(is_array(json_decode($data['store_file_path'], true)) ? json_decode($data['store_file_path'], true) : []);
        $data['soft_base_fee'] = intval($data['soft_base_fee']);
        $data['soft_year_fee'] = intval($data['soft_year_fee']);
        SiteStore::where(['id' => $req_data['id']])->update($data);

        //更新到期时间
        Redis::set('store_timeout_at_byid_' . intval($req_data['id']), intval($data['contract_end_at']));

        return response()->json(['code' => '000', 'msg' => '编辑门店成功']);
    }

    /**
     * 门店补全合同信息
     */
    public function docontractinfo(Request $request)
    {
        $req_data = $request->only(['id', 'soft_year_fee', 'contract_at', 'contact_name', 'contract_end_at', 'pay_at', 'pay_type', 'pay_type_name', 'contract_type', 'business_mem_id', 'contract_file_path', 'store_file_path', 'remark']);


        $Validate = new ValidateAccountStore('contractinfo');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $info = SiteStore::where([['id', $req_data['id']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '门店参数错误']);
        }
        $data = $req_data;
        unset($data['id']);
        $data['update_at'] = time();
        // $data['audit_status'] = 2;

        $data['pay_type'] = empty($data['pay_type']) ? 0 : $data['pay_type'];
        $data['business_mem_id'] = empty($data['business_mem_id']) ? 0 : $data['business_mem_id'];
        $data['contract_type'] = (isset($data['contract_type']) && in_array($data['contract_type'], [1, 2])) ? $data['contract_type'] : 1;

        $data['pay_at'] = strtotime($data['pay_at']) > 0 ? strtotime($data['pay_at']) : intval($data['pay_at']);
        $data['contract_at'] = strtotime($data['contract_at']) > 0 ? strtotime($data['contract_at']) : intval($data['contract_at']);
        $data['contract_end_at'] = strtotime($data['contract_end_at']) > 0 ? strtotime($data['contract_end_at']) : intval($data['contract_end_at']);
        $data['contract_file_path'] = is_array($data['contract_file_path']) ? json_encode($data['contract_file_path']) : (is_array(json_decode($data['contract_file_path'], true)) ? $data['contract_file_path'] : json_encode([]));
        $data['store_file_path'] = isset($data['store_file_path']) ? $data['store_file_path'] : '';
        $data['store_file_path'] = is_array($data['store_file_path']) ? json_encode($data['store_file_path']) : (is_array(json_decode($data['store_file_path'], true)) ? $data['store_file_path'] : json_encode([]));
        if ($data['contract_end_at'] <= time()) {
            return response()->json(['code' => '001', 'msg' => '无效到期时间']);
        }

        if (($info->contract_at == 0 && $data['contract_at'] > 0) || ($info->soft_year_fee != $data['soft_year_fee']) || ($data['contract_end_at'] != $info->contract_end_at) || $info->contract_audit_status == 4 || $info->contract_audit_status == 1) {
            $data['contract_audit_status'] = 2;
        }

        if ($info->audit_status == 4) { //审核取消后，编辑完成自动变成审核中，需要再次审核
            $data['audit_status'] = 2;
        }
        SiteStore::where(['id' => $req_data['id']])->update($data);

        return response()->json(['code' => '000', 'msg' => '添加合同成功']);
    }


    public function dodel(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteStore::where([['id', $id], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $accountlist = Account::where(['store_ids' => $info->id])->get()->toArray();
        DB::beginTransaction();
        try {
            SiteStore::where(['id' => $id])->update(['is_del' => 2, 'del_at' => time()]);

            foreach ($accountlist as $val) {
                Account::where(['id' => $val['id']])->update(['is_del' => 2, 'del_at' => time()]);
                Common::cleartokenkey($val['id']);
                Common::cleartokenkeybywxapp($val['id']);
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '操作失败']);
        }


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 审核成功
     */
    public function doauditsuccess(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteStore::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 2) {
            return response()->json(['code' => '001', 'msg' => '门店信息状态未处于待审核']);
        }
        SiteStore::where([['id', $id]])->update(['audit_status' => 3, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 审核取消--失败重新编辑
     */
    public function doauditcancel(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteStore::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 2) {
            return response()->json(['code' => '001', 'msg' => '门店信息状态未处于待审核']);
        }
        SiteStore::where([['id', $id]])->update(['audit_status' => 4, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    /**
     * 合同审核成功
     */
    public function docontractauditsuccess(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteStore::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->contract_audit_status != 2) {
            return response()->json(['code' => '001', 'msg' => '门店合同信息状态未处于待审核']);
        }
        SiteStore::where([['id', $id]])->update(['contract_audit_status' => 3, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 合同审核取消--失败重新编辑
     */
    public function docontractauditcancel(Request $request)
    {
        $id = $request->id ?? 0;
        $info = SiteStore::where([['id', $id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->contract_audit_status != 2) {
            return response()->json(['code' => '001', 'msg' => '门店合同信息状态未处于待审核']);
        }
        SiteStore::where([['id', $id]])->update(['contract_audit_status' => 4, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 更换门店所属公司--有数据了处理
     */
    public function changestorecompany(Request $request)
    {
        $store_id = intval($request->store_id);
        $target_cp_id = intval($request->target_cp_id);
        $info = SiteStore::where([['id', $store_id]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($target_cp_id <= 0 || $target_cp_id == $info->cp_id) {
            return response()->json(['code' => '001', 'msg' => '无效目标门店']);
        }

        $cpinfo = SiteCompany::where(['id' => $target_cp_id])->first();
        if (!$cpinfo) {
            return response()->json(['code' => '001', 'msg' => '无效目标门店']);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']); //等开发完成测试

        //甲公司的A门店所有数据转到乙公司，甲不保留数据，更改门店所有相关的数据cp_id为目标门店
        $tablelist = DB::select("SELECT DISTINCT TABLE_NAME FROM information_schema.COLUMNS WHERE COLUMN_NAME = 'store_id' and TABLE_SCHEMA='" . env('DB_DATABASE') . "'");
        DB::beginTransaction();
        try {
            foreach ($tablelist as $table) {
                $tablename = str_replace(env('DB_PREFIX', ''), '', $table->TABLE_NAME);
                DB::table($tablename)->where(['store_id' => $store_id])->update(['cp_id' => $target_cp_id]); //更改数据的所属公司
            }
            SiteStore::where(['id' => $store_id])->update(['cp_id' => $target_cp_id]); //更改门店的所属公司
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('更换门店失败' . $e->getMessage());
            return response()->json(['code' => '001', 'msg' => '更换门店失败']);
        }

        //清除门店所有人员登录状态
        $accountlist = Account::where(['store_ids' => $store_id])->get()->toArray(); //股东、公司管理员、财务等保持原样、多余数据会根据所属公司变更

        foreach ($accountlist as $val) {
            Common::cleartokenkey($val['id']);
            Common::cleartokenkeybywxapp($val['id']);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    { //isgetall=1;
        $list = SiteStore::getList($request)['list'];
        $exceldata = [];
        if ($request->type == 1) {
            $title = '用户门店列表';
            $row = [
                ['company_name' => $title],
                [
                    'store_name' => '门店名称',
                    'company_name' => '所属公司',
                    'contact_name' => '负责人姓名',
                    'contact_phone' => '负责人电话',
                    'address_area' => '归属区域',
                    'is_can_use' => '是否可用',
                    'brand_name' => '门店品牌',
                    'business_mem_name' => '业务员',
                    'customer_service_name' => '客服',
                    'end_days' => '到期天数',
                    'soft_base_fee' => '软件费',
                    'soft_year_fee' => '年费',
                    'contract_at' => '合同签订日期',
                    'contract_years' => '合同年限',
                    'contract_end_at' => '合同到期日期',
                    'create_at' => '创建时间',
                    'update_at' => '修改时间',
                    'audit_status' => '审核状态',
                    // 'contract_audit_status' => '合同审核状态',
                    'remark' => '备注',
                ]
            ];
        } else {
            $title = '门店OA审批列表';
            $row = [
                ['company_name' => $title],
                [
                    'store_name' => '门店名称',
                    'company_name' => '所属公司',
                    'contact_name' => '负责人姓名',
                    'contact_phone' => '负责人电话',
                    'address_area' => '归属区域',
                    'is_can_use' => '是否可用',
                    'brand_name' => '门店品牌',
                    'business_mem_name' => '业务员',
                    'customer_service_name' => '客服',
                    'soft_base_fee' => '软件费',
                    'soft_year_fee' => '年费',
                    'contract_at' => '合同签订日期',
                    'contract_years' => '合同年限',
                    'contract_end_at' => '合同到期日期',
                    'create_at' => '创建时间',
                    'update_at' => '修改时间',
                    'audit_status' => '审核状态',
                    // 'contract_audit_status' => '合同审核状态',
                    'remark' => '备注',
                ]
            ];
        }

        foreach ($list as $val) {
            $col = [
                'store_name' => $val['store_name'],
                'company_name' => $val['companyinfo']['company_name'],
                'contact_name' => $val['companyinfo']['contact_name'],
                'contact_phone' => $val['companyinfo']['contact_phone'],
                'address_area' => $val['address_area'],
                'is_can_use' => $val['is_can_use'] == 1 ? '是' : '否',
                'brand_name' => isset($val['brandinfo']['brand_name']) ? $val['brandinfo']['brand_name'] : '--',
                'business_mem_name' => isset($val['businessmeminfo']['mem_name']) ? $val['businessmeminfo']['mem_name'] : '--',
                'customer_service_name' => isset($val['customerserviceinfo']['mem_name']) ? $val['customerserviceinfo']['mem_name'] : '--',
                'soft_base_fee' => $val['soft_base_fee'] / 100,
                'soft_year_fee' => $val['soft_year_fee'] / 100,
                'contract_at' => $val['contract_at'] > 0 ? date('Y-m-d', $val['contract_at']) : '--',
                'contract_years' => $val['contract_years'],
                'contract_end_at' => $val['contract_end_at'] > 0 ? date('Y-m-d', $val['contract_end_at']) : '--',
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'update_at' => date('Y-m-d H:i:s', $val['update_at']),
                'audit_status' => $val['audit_status'] == 2 ? '审核中' : ($val['audit_status'] == 3 ? '审核成功' : '审核取消'),
                'contract_audit_status' => $val['contract_audit_status'] == 1 ? '未提交审核' : ($val['contract_audit_status'] == 2 ? '审核中' : ($val['contract_audit_status'] == 3 ? '审核成功' : '审核取消')),
                'remark' => $val['remark'],
                'end_days' => $val['end_days'] = ceil(($val['contract_end_at'] - time()) / 86400),
            ];

            $exceldata[] = $col;

        }

        $filename = $title . '导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    public function doexportwithcontractaudit(Request $request)
    { //isgetall=1;
        $list = SiteStore::getList($request)['list'];
        $exceldata = [];
        $row = [

            ['company_name' => '合同审批列表'],
            [
                'company_name' => '所属公司',
                'store_name' => '用户门店',
                'contact_name' => '负责人',
                'contact_phone' => '负责人电话',
                'contract_at' => '续费前日期',
                'contract_end_at' => '合同续期时间',
                'pay_type' => '收款方式',
                'pay_at' => '收款时间',
                'soft_year_fee' => '合同金额',
                'contract_type' => '合同类型',
                'business_mem_name' => '业务员',
                'customer_service_name' => '客服',
                'create_at' => '创建时间',
                'remark' => '备注',
                'contract_audit_status' => '审核状态'
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'company_name' => $val['companyinfo']['company_name'],
                'store_name' => $val['store_name'],
                'contact_name' => $val['companyinfo']['contact_name'],
                'contact_phone' => $val['companyinfo']['contact_phone'],
                'contract_at' => $val['contract_at'] > 0 ? date('Y-m-d', $val['contract_at']) : '--',
                'contract_end_at' => $val['contract_end_at'] > 0 ? date('Y-m-d', $val['contract_end_at']) : '--',
                'pay_type' => isset($val['paytypeinfo']['paytype_name']) ? $val['paytypeinfo']['paytype_name'] : '--',
                'pay_at' => date('Y-m-d H:i:s', $val['pay_at']),
                'soft_year_fee' => $val['soft_year_fee'] / 100,
                'contract_type' => $val['contract_type'] == 1 ? '新户合同' : '续费合同',
                'business_mem_name' => isset($val['businessmeminfo']['mem_name']) ? $val['businessmeminfo']['mem_name'] : '--',
                'customer_service_name' => isset($val['customerserviceinfo']['mem_name']) ? $val['customerserviceinfo']['mem_name'] : '--',
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
                'remark' => $val['remark'],
                'contract_audit_status' => $val['contract_audit_status'] == 1 ? '未提交审核' : ($val['contract_audit_status'] == 2 ? '未审核' : ($val['contract_audit_status'] == 3 ? '审核成功' : '审核取消'))
            ];
        }

        $filename = '合同审批列表导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    public function addCategoryDefault($params)
    {
        $cabinetList = GoodsCabinetgroup::query()
            ->where('cp_id', $params['cp_id'])
            ->where('is_del', 1)
            ->get(['id', 'cabinetgroup_name'])
            ->pluck('id', 'cabinetgroup_name')
            ->toArray();

        $metalList = GoodsMetal::query()
            ->where('cp_id', $params['cp_id'])
            ->where('is_del', 1)
            ->get(['id', 'metal_name'])
            ->pluck('id', 'metal_name')
            ->toArray();
        $default = SiteDefaultCategory::query()->get();
        $categoryData = [];
        foreach ($default as $item) {
            $categoryData[] = [
                'cp_id' => $params['cp_id'],
                'store_id' => $params['store_id'],
                'category_name' => $item['cate_name'],
                'goods_cabinetgroup_id' => $cabinetList[$item['cabinet']] ?? 0,
                'goods_metal_id' => $metalList[$item['metal']] ?? 0,
                'is_recovery' => $item['is_recovery'],
                'is_sujin' => $item['is_sujin'],
                'is_virtually' => $item['is_virtually'],
                'is_maintenance_price' => $item['is_maintenance_price'],
                'is_gram' => $item['is_gram'],
                'remark' => empty($item['remark']) ? '' : $item['remark'],
                'create_at' => time(),
            ];
        }

        GoodsCategory::query()
            ->insert($categoryData);


    }
}
